<template>
  <Form
    :label-width="80"
    ref="formValidate"
    :rules="ruleValidate"
    :model="formValidate"
  >
    <FormItem label="角色名称" prop="roleName">
      <i-input
        type="text"
        v-show="type !== 3"
        v-model="formValidate.roleName"
        placeholder="请输入角色名称"
      >
      </i-input>
      <span v-show="type === 3">{{formValidate.roleName}}</span>
    </FormItem>
    <FormItem label="所属单位">
      <Select v-model="formValidate.fkOrgId" v-show="type !== 3">
        <Option v-for="item in unitList" :value="item.id" :key="item.id">{{ item.orgName }}</Option>
      </Select>
      <span v-show="type === 3">{{orgName}}</span>
    </FormItem>
    <FormItem label="备注">
      <i-input
        type="textarea"
        v-show="type !== 3"
        v-model="formValidate.memo"
        placeholder="备注"
        :disabled="type === 3"
      >
      </i-input>
      <span v-show="type === 3">{{formValidate.memo}}</span>
    </FormItem>
    <FormItem prop="memo" label="创建人" v-show="type === 3">
       <span>{{formValidateView.createUserName}}</span>
    </FormItem>
    <FormItem prop="memo" label="创建时间" v-show="type === 3">
       <span>{{formValidateView.gmtCreate}}</span>
    </FormItem>
    <FormItem prop="memo" label="修改人" v-show="type === 3">
       <span>{{formValidateView.updateUserName}}</span>
    </FormItem>
    <FormItem prop="memo" label="修改时间" v-show="type === 3">
       <span>{{formValidateView.gmtModified}}</span>
    </FormItem>
    <!-- <template>
      <dl v-for="(menu, index) in menuList" :key="'one' + index">
        <TemplatePermission :menu="menu" :permissionMap="permissionMap" :type="type"/>
      </dl>
    </template> -->
    <el-tree
      :data="treeData"
      node-key="id"
      :default-expand-all="true"
      show-checkbox
      ref="elTree"
      :expand-on-click-node="false"
      :props="defaultProps">
    </el-tree>
    <FormItem :label-width="0" style="margin-top: 20px;">
      <Button
        type="primary"
        @click="publicSubmit('formValidate')"
        v-if="type !== 3"
        style="margin-right: 8px"
      >确定
      </Button>
      <Button @click="publicReset('formValidate')">取消</Button>
    </FormItem>
  </Form>
</template>

<script>
import API_KEY from '../../../api'
import { createRoleData, getRoleMenu, updateRoleData, getRoleById } from '../../../api/modules/user/role'
import message from '../../../utils/message'
import { typeOf } from '../../../utils/verification'

export default {
  name: 'RoleManageUpdate',
  props: {
    type: {
      type: Number,
      required: true
    },
    // 模块id必须传
    moduleId: {
      type: [String, Number],
      required: true
    },
    // 模块id名称必须传
    idName: {
      type: String,
      required: true
    },
    unitList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  computed: {
    orgName () {
      const arr = this.unitList.filter(item => item.id === this.formValidate.fkOrgId)
      if (arr.length > 0) {
        return arr[0].orgName
      }
      return ''
    }
  },
  data () {
    return {
      // 表单数据
      formValidate: {
        roleName: '',
        roleType: '',
        fkOrgId: '',
        memo: '',
        permissionList: []
      },
      formValidateView: {},
      // 权限数据,复选框数据的存入
      permissionMap: {},
      // 表单校验规则
      ruleValidate: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      action: {
        // 根据id获取数据（如果使用混入，属性名不能变，所在位置不能变,下同）
        // 新增数据
        createData: API_KEY.role.curdRole,
        // 更新数据
        updateData: API_KEY.role.curdRole
      },
      menuList: [],
      suffix: '角色信息',
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  updated () {
    this.updateNodeTayout()
  },
  mounted () {
    if (this.type !== -1) {
      this.getRoleMenu()
      if (this.type !== 1) {
        this.$_getRoleById(this.moduleId)
      }
      if (this.type === 2) {
        this.formValidate.version = ''
        this.formValidate.id = ''
      }
    }
  },
  methods: {
    // 获取角色权限菜单
    getRoleMenu () {
      getRoleMenu().then(({ data }) => {
        let arr = []
        if (this.type === 3) {
          arr = formatData(data, true)
        } else {
          arr = formatData(data, false)
        }
        // console.log(arr)
        this.treeData = arr
      })
    },
    /**
     * 数据提交
     * @param name
     */
    publicSubmit (name) {
      if (name) {
        // 判断校验是否通过
        this.$refs[name].validate((valid) => {
          if (valid) {
            let checkBox = []
            if (this.$refs.elTree) {
              checkBox = this.$refs.elTree.getCheckedKeys() || []
            }
            let permissionList = []
            checkBox.forEach(item => {
              const arr = item.split('$$')
              if (arr.length > 1) {
                const key = arr[0]
                const filterArr = permissionList.filter(item => item.fkMenuCode === key)
                if (filterArr.length > 0) {
                  filterArr[0].permissionValue.push(arr[1])
                } else {
                  permissionList.push({
                    fkMenuCode: arr[0],
                    permissionValue: [arr[1]]
                  })
                }
              }
            })
            permissionList = permissionList.map(item => {
              return {
                fkMenuCode: item.fkMenuCode,
                permissionValue: item.permissionValue.join(',')
              }
            })
            this.formValidate.permissionList = permissionList
            // 直接请求数据
            this.$_submitData(this.formValidate)
          } else {
            message.message.error('数据格式不正确，请检查后重试')
          }
        })
      }
    },
    $_submitData (params) {
      if (this.type === 1) {
        // 发送请求
        createRoleData(params).then(data => {
          message.message.success(data.message)
          // 请求成功，关闭视图并重新请求数据
          this.$emit('closeView', 1)
        })
      } else if (this.type === 2) {
        // 发送请求
        updateRoleData(params).then(data => {
          message.message.success(data.message)
          // 请求成功，关闭视图并重新请求数据
          this.$emit('closeView', 1)
        })
      }
    },
    publicReset (name) {
      if (name) {
        // 清空表单，关闭视图
        this.$refs[name].resetFields()
        this.$emit('closeView')
      }
    },
    /**
     * 根据id获取角色信息
     */
    $_getRoleById (id) {
      getRoleById(id).then(({ data }) => {
        const permissionList = data.permissionList || []
        const checkBox = []
        permissionList.forEach(item => {
          if (typeOf(item.permissionValue) === 'string') {
            const permissionValue = item.permissionValue.split(',')
            permissionValue.forEach(item1 => {
              checkBox.push(item.fkMenuCode + '$$' + item1)
            })
          }
        })
        this.$nextTick(() => {
          this.$refs.elTree.setCheckedKeys(checkBox)
        })
        Object.keys(this.formValidate).forEach(item => {
          if (item !== 'permissionList') {
            this.formValidate[item] = data[item]
          }
        })
        this.formValidateView = data
      })
    },
    /**
     * 更新dom
     */
    updateNodeTayout () {
      this.$nextTick(() => {
        const isLeaf = this.$el.querySelectorAll('.is-leaf') || []
        isLeaf.forEach(item => {
          const rootNode = ((item.parentNode || {}).parentNode || {}).parentNode || {}
          const parentNode = item.parentNode || {}
          parentNode.style.paddingLeft = '0px'
          if (typeOf(rootNode.getAttribute) === 'function' && rootNode.getAttribute('class') !== 'el-tree') {
            rootNode.style.display = 'flex'
            const firstChild = (rootNode.firstElementChild || {}).firstElementChild
            firstChild.style.paddingLeft = '60px'
          }
        })
      })
    }
  }
}
/**
 * 将数据处理为树形菜单需要的数据
 */
function formatData (arr, flag = false) {
  return arr.map(item => {
    let obj = {}
    if (item.permissions) {
      obj = {
        id: item.menuCode,
        label: item.menuName,
        isLeaf: true,
        disabled: flag,
        children: item.permissions.split(',').map(item1 => {
          return {
            id: item.menuCode + '$$' + item1,
            label: item1,
            disabled: flag
          }
        })
      }
    } else {
      obj = {
        id: item.menuCode,
        isLeaf: false,
        disabled: flag,
        label: item.menuName,
        children: []
      }
    }
    if (item.children && item.children.length > 0) {
      obj.children = formatData(item.children, flag)
    }
    return obj
  })
}
</script>

<style lang="scss" scoped>
/deep/ .expanded{
  display: none;
}
</style>
